<!-- 业务步骤批量导入 -->
<template>
	<div class="container">
		<el-row :gutter="10" style="margin-bottom: 20px">
			<el-col :span="7">
				<el-date-picker
					v-model="dateRange"
					value-format="YYYY-MM-DD HH:mm:00"
					type="datetimerange"
					range-separator="-"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					:clearable="false"
				></el-date-picker>
			</el-col>
			<el-col :span="14">
				<el-button @click="handlerQuery" type="primary" icon="Search"> 查 询 </el-button>
				<el-button @click="openUpload" icon="Upload"> 导 入 </el-button>
			</el-col>
		</el-row>

		<YdTable
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="queryList"
			@currentChangeHandler="queryList"
			@sortChangeHandler="queryList"
			@selectionChangeHandler="queryList"
		></YdTable>

		<div class="detailTitle">
			<h4>
				导入业务结果
				<el-tooltip effect="light" content="如需修改步骤类型，请到业务配置菜单对应的业务进行修改" placement="top-start" style="z-index: 999">
					<i class="question-icon">
						<svg-icon icon-class="question"></svg-icon>
					</i>
				</el-tooltip>
			</h4>
		</div>

		<YdTable
			:formData="queryParams2"
			:tableConfig="detailTableConfig"
			:tableData="tableData2.data"
			@selectionChangeHandler="handlerQuery2"
			@sizeChangeHandler="handlerQuery2"
			@currentChangeHandler="handlerQuery2"
		></YdTable>

		<!-- 批量导入 -->
		<el-dialog title="批量导入" v-model="uploadOpen" width="700px" :close-on-click-modal="false" append-to-body center>
			<div style="text-align: center">
				<el-upload
					action="#"
					:limit="1"
					accept=".xlsx,.xls"
					:on-success="handlerSuccess"
					:on-change="fileChange"
					:on-remove="handlerRemove"
					:on-error="handlerError"
					:file-list="fileList"
					:auto-upload="false"
					drag
				>
					<el-icon class="el-icon--upload"><upload-filled /></el-icon>
					<div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
				</el-upload>
			</div>

			<template #footer>
				<el-button type="primary" @click="handlerDownloadTemplate">下载模板</el-button>
				<el-button type="primary" @click="submitUploadForm" :loading="uploadLoading">确定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="BusinessStepBatchImport" lang="tsx">
import { list, getTemplate, getList, upload, download4List } from '@/api/admin/businessMonitor/businessStepBatchImport';
import { downloadFromBlob, parseTime } from '@/utils/common';
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

const { proxy }: any = getCurrentInstance();
const router = useRouter();

const uploadLoading = ref(false);
const dateRange = ref([
	parseTime(new Date().getTime() - 1000 * 60 * 60 * 24 * 5, '{y}-{m}-{d} 00:00:00'),
	parseTime(new Date().getTime() + 1000 * 60 * 60 * 24, '{y}-{m}-{d} 00:00:00'),
]);
// 查询参数
let queryParams = reactive({
	pageNum: 1,
	pageSize: 10,
});
// 列表数据
let tableData = reactive({
	data: [],
	total: 0,
});
let tableConfig = reactive({
	url: list,
	columns: [
		{
			label: '帐号',
			prop: 'createBy',
			width: 180,
		},
		{
			label: '导入时间',
			prop: 'createTime',
		},
		{
			label: '流水号',
			prop: 'dataNumber',
		},
		{
			label: '处理状态',
			prop: 'dealStatus',
			renderXss: (row: any, val: any) => {
				let color = '';
				if (val === '1') {
					val = '处理完成';
				} else {
					color = 'red';
					val = '处理中';
				}
				const cls = { color: color };
				return <span style={cls}>{val}</span>;
			},
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '查看明细',
					handler: (scope: any) => getDetailHandle(scope.row),
				},
				{
					text: '导出',
					handler: (scope: any) => downLoadExcel(scope.row),
				},
			],
		},
	],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
	// 关闭序号
	disableOrderNumber: false,
});
let queryParams2 = reactive<any>({
	pageNum: 1,
	pageSize: 10,
});
let tableData2 = reactive<any>({
	data: [],
	total: 0,
});
const detailTableConfig = reactive<any>({
	url: getList,
	columns: [
		{
			label: '流水号',
			prop: 'dataNumber',
			width: 180,
		},
		{
			label: '序号',
			prop: 'sequenceNumber',
			width: 180,
		},
		{
			label: '系统名称',
			prop: 'systemName',
			width: 180,
		},
		{
			label: '业务名称',
			prop: 'businessName',
			width: 350,
			operation: [
				{
					text: undefined,
					rowKey: 'businessName',
					handler: (scope: any) => {
						router.push({
							path: '/management/businessManage/businessConfig',
							query: {
								systemId: scope.row.systemCode,
								name: scope.row.businessName,
							},
						});
					},
				},
			],
		},
		{
			label: '状态',
			prop: 'businessStatus',
			width: 180,
			renderXss: (row: any, val: any) => {
				if (row.dealStatus == -1) {
					return '';
				} else {
					let color1 = '';
					let color2 = '';
					let stepStatusval = '';
					if (val === 0) {
						val = '业务成功';
					} else {
						color1 = 'red';
						val = '业务失败';
					}
					if (row.stepStatus == 0) {
						stepStatusval = '步骤成功';
					} else if (row.stepStatus === 1) {
						stepStatusval = '步骤全部失败';
						color2 = 'red';
					} else if (row.stepStatus === 2) {
						stepStatusval = '步骤部分失败';
						color2 = 'red';
					}
					const cls = {
						color: color1,
					};
					const cls2 = {
						color: color2,
					};
					return (
						<span>
							<span style={cls}>{val} </span>
							<span style={cls2}>{stepStatusval} </span>
						</span>
					);
				}
			},
		},
		{
			label: '详细信息',
			prop: 'stepInfo',
			width: 180,
			showOverFlowToolTip: true,
			operation: [
				{
					text: '明细数据',
					rowKey: 'stepInfo',
					handler: (scope: any) => {
						router.push({
							// path: '/admin/businessMonitor/busiStepDetails',
							path: '/management/dataManage/businessStepBatchImportDetails',
							query: {
								dataNumber: scope.row.dataNumber,
								sequenceNumber: scope.row.sequenceNumber,
							},
						});
					},
				},
			],
		},
		{
			label: '失败原因',
			prop: 'reason',
			showOverFlowToolTip: true,
		},
	],
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
	// 关闭序号
	disableOrderNumber: true,
});
const uploadOpen = ref(false);
const fileList = ref([] as any);

/** 搜索按钮操作 */
function handlerQuery() {
	queryList();
}
/** 查询列表 */
function queryList() {
	tableConfig.loading = true;
	list({
		...queryParams,
		startTime: dateRange.value[0],
		endTime: dateRange.value[1],
	})
		.then((response: ApiResponse | any) => {
			tableConfig.loading = false;
			if (response.code != 0) {
				proxy.$modal.msgError(response.msg);
				return;
			}
			if (response.data.records.length > 0) {
				tableData.data = response.data.records;
				tableConfig.pagination.total = response.data.total;
				queryParams2.dataNumber = response.data.records[0].dataNumber;
				queryParams2.dealStatus = response.data.records[0].dealStatus;
				getProcessList();
			} else {
				tableData.data = [];
				tableConfig.pagination.total = 0;
				detailTableConfig.loading = false;
				tableData2.data = [];
				tableData2.total = 0;
			}
		})
		.catch((e: any) => {
			detailTableConfig.loading = false;
			tableConfig.loading = false;
		});
}
//批量导入
function openUpload() {
	uploadOpen.value = true;
}
//取消
function cancel() {
	uploadOpen.value = false;
	fileList.value = [];
}
/*下载模板*/
function handlerDownloadTemplate() {
	getTemplate().then((response) => {
		downloadFromBlob(response, '批量导入模板');
	});
}
function fileChange(file: any) {
	fileList.value[0] = file.raw;
}
function handlerRemove() {
	fileList.value = [];
}
function handlerSuccess() {
	proxy.$modal.msgSuccess('上传成功，点击确认导入!');
	fileList.value = [];
}
function handlerError() {
	proxy.$modal.msgError('上传失败');
}
/** 导入提交按钮 */
function submitUploadForm() {
	if (fileList.value[0]) {
		let form = new FormData();
		const isXLS =
			fileList.value[0].type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
			fileList.value[0].type === 'application/vnd.ms-sheet' ||
			fileList.value[0].type === 'application/vnd.ms-excel';
		if (!isXLS) {
			proxy.$modal.msgError('请上传Excel文件');
			return;
		}
		const isLt5M = fileList.value[0].size / 1024 / 1024 < 5;
		if (!isLt5M) {
			proxy.$modal.msgError('文件大小不能超过5M');
			return;
		}
		form.append('file', fileList.value[0]);
		uploadLoading.value = true;
		upload(form).then((rs: ApiResponse | any) => {
			if (rs.code === 0) {
				handlerQuery();
				proxy.$modal.msgWarning('导入模板处理时间需要1分钟,请手动刷新页面');
			} else {
				proxy.$modal.msgError(rs.msg);
				fileList.value = [];
			}
			uploadOpen.value = false;
			uploadLoading.value = false;
			fileList.value = [];
		});
	} else {
		proxy.$modal.msgWarning('请先上传文件');
	}
}
//查看明细
function getDetailHandle(obj: any) {
	queryParams2.dataNumber = obj.dataNumber;
	queryParams2.dealStatus = obj.dealStatus;
	getProcessList();
}
//导出
function downLoadExcel(obj: any) {
	download4List(obj.dataNumber).then((res) => {
		downloadFromBlob(res, '导入业务结果').then((o) => {
			if (!o.flag) {
				proxy.$mdal.msgWarning(o.msg);
			}
		});
	});
}
function handlerQuery2() {
	getProcessList();
}
//导入业务结果列表
function getProcessList() {
	detailTableConfig.loading = true;
	var req = {
		dataNumber: queryParams2.dataNumber,
		pageNum: queryParams2.pageNum,
		pageSize: queryParams2.pageSize,
	};
	getList(req).then((response: ApiResponse | any) => {
		if (response.code != 0) {
			proxy.$modal.msgError(response.msg);
			return;
		}
		for (var i of response.data.records) {
			if (queryParams2.dealStatus != 1) {
				i.dealStatus = -1;
			}
		}
		detailTableConfig.loading = false;
		tableData2.data = response.data.records;
		detailTableConfig.pagination.total = response.data.total;
	});
}
handlerQuery();
</script>

<style lang="scss" scoped>
.detailTitle {
	height: 40px;
	line-height: 40px;
	margin-bottom: 10px;
	margin-left: 25px;
}
.table {
	padding: 0 0 0 20px;
}
</style>
